package com.ly.mpayment.rest.up.hunanjb;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 回调接口
 */
@Component
@Path("hunanjb")
public class HuNanJob {

    Logger logger = Logger.getLogger(HuNanJob.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    /**
     * @return
     */
    @Path("callBack")
    @POST
    public synchronized String callBack(@RequestBody String body){
        logger.info("hunanjb:"+body);
        if(!StringUtils.isBlank(body)){
            /**
             * //回传
             * {
             *     "data":[
             *     {
             *         "orderNum":"4028b88160a68a090160a68c92640001",
             *  	"phonenum":"18733334444",
             *         "createtime":"2016-11-30 16:31:58",
             *     	"facevalue":5,
             * "status":2//2成功 3失败
             *     },

             * ],
             *     "code":"1000",
             *     "sign":"签名",
             *     "ts":"年月日时分秒",
             *    "appid":"appid" //我们提供appid 和appkey 来进行签名加密 提供签名算法
             * }
             */
            JSONObject jsonObject = JSONObject.parseObject(body);
            if(jsonObject.containsKey("code") && !jsonObject.getString("code").equals("1000")){
                return "";
            }
            //验证签名

            final UpShopInfo upShopInfo = upShopInfoService.findByAppId(jsonObject.getString("appid"));
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+jsonObject.getString("appid"));
                return "1";
            }

            //md5(code + ts + appid + appkey ) 小写
            if(!jsonObject.getString("sign").equalsIgnoreCase(MD5.md5(jsonObject.getString("code")+jsonObject.getString("ts")
                    +jsonObject.getString("appid")+upShopInfo.getUpkey()))){
                logger.info("签名错误:"+jsonObject.getString("appid"));
                return "1";
            }
            JSONArray array = jsonObject.getJSONArray("data");
            if(CollectionUtils.isEmpty(array)){
                return "2";
            }
            for(int i = 0 ; i < array.size(); i++){
                JSONObject json = array.getJSONObject(i);

                UpOrder order = upOrderService.findById(json.getString("orderNum"));
                //掉线
                if(json.containsKey("error_status") && json.getString("error_status").equals("offline")){
                    upOrderService.addOrderMsg(order,"工号掉线"+json.getString("phonenum"));
                    break;
                }
                if (order != null && json.getString("status").equals("2") && order.getStatus() == Config.status[0]) {
                    order.setRemark(json.getString("status"));
                    RechargeRest.successUpOrder.add(order);
                }else if(order != null && order.getStatus() == Config.status[0] && json.getString("status").equals("3")){
                    order.setRemark(json.getString("status"));
                    RechargeRest.failtUpOrder.add(order);
                }else{
                    logger.info("sichuan_not_found_order:" + body +","+ (order == null ? " order is null" : order.getUpphonenum() ));
                }
            }
            return "ok";
        }
        return "failt";
    }

    /**
     * 订单提交
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        //{"phoneNum":"18684900018","orderId":"1111","money":"12"}
        JSONObject body = new JSONObject();
        body.put("phoneNum",order.getUpphonenum());
        body.put("orderId",order.getUporderuuid());
        body.put("money",order.getRechargeamount().intValue());
        body.put("sign",MD5.md5(shop.getAppId()+"phoneNum="+order.getUpphonenum()+"&orderId="+order.getUporderuuid()+
                "&money="+order.getRechargeamount().intValue()+shop.getUpkey()));
        try{
            String result = HttpRequest.post(shop.getOrderCommitAddress()).execute().body();
            if(!StringUtils.isBlank(result)){
            //{"code": 0,"msg": "success","data": {"phoneNum": "18684900018","orderId": "111","money": "12","state": "4"}}
                JSONObject json = JSONObject.parseObject(result);
                if(json.containsKey("code")){
                    if(json.getString("code").equals("0")){
                        order.setRemark("充值成功");
                        RechargeRest.successUpOrder.add(order);
                    } else if(json.getString("code").equals("3")){
                        order.setRemark("失败");
                        RechargeRest.failtUpOrder.add(order);
                    } else if(json.getString("code").equals("4")){
                        order.setRemark("余额不足");
                        RechargeRest.failtUpOrder.add(order);
                    } else if(json.getString("code").equals("5")){
                        order.setRemark("签名错误");
                        RechargeRest.failtUpOrder.add(order);
                    }
                }else{
                    this.upOrderService.updateUpOrderArtificial(order,"","订单异常,人工核实");
                }
            }else{
                this.upOrderService.updateUpOrderArtificial(order,"","订单异常,人工核实");
            }
        }catch (Exception e){
            order.setRemark("提单失败");
            RechargeRest.failtUpOrder.add(order);
        }
    }
    /**
     * 查询待处理待订单
     * @param body
     * @return
     */
    @Path("queryOrder")
    @POST
    public synchronized String saveOrder(@RequestBody String body) {
        logger.info("sichuan:"+body);
        try{
            JSONObject data = JSONObject.parseObject(body);
            //营业厅id 营业厅数据存放号码金额时间 状态
            data.getString("appId");

            UpShopInfo upShopInfo = upShopInfoService.findByAppId(CookieRedis.get("hunanjb_useruuid"));
            if(upShopInfo == null || upShopInfo.getQuerySwitch() == false){
                return ResultMessage.getFailt(" 账户未开启");
            }
            Map<String, Object> parameters = new HashMap<>();
            parameters.put(":useruuid",upShopInfo.getUser().getUseruuid() );
            parameters.put(":status", 5);
            int pageSize = CookieRedis.get("hunanjb_size") == null ? 10 : Integer.valueOf(CookieRedis.get("hunanjb_size"));
            List<UpOrder> list = upOrderService.savePageOrderQh(parameters,0,pageSize,false);
            JSONArray array = new JSONArray();
            if(!CollectionUtils.isEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    UpOrder upOrder = list.get(i);
                    upOrder = this.upOrderService.findById(upOrder.getUporderuuid());
                    if(upOrder.getStatus() == 1){
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("orderNum", upOrder.getUporderuuid());
                        jsonObject.put("phonenum", upOrder.getUpphonenum());
                        jsonObject.put("createtime", DateUtils.toLongDate(upOrder.getCreatetime()));
                        jsonObject.put("facevalue", upOrder.getRechargeamount());
                        array.add(jsonObject);
                        logger.info("queryphone:"+upOrder.getUpphonenum()+","+upOrder.getStatus());
                    }
                }
            }
            logger.info("queryOrder:"+array.toString());
            return ResultMessage.getSucceed(array.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONArray array = new JSONArray();
        return ResultMessage.getSucceed(array.toString());
    }

    /**
     * 查询待处理待订单
     * @param body
     * @return
     */
    @Path("queryOrderDetail")
    @POST
    public synchronized String queryOrderDetail(@RequestBody String body) {
        logger.info("queryhunanjbOrderDetail:"+body);
        if(!StringUtils.isBlank(body)){
            JSONObject jsonObject = JSONObject.parseObject(body);
            UpOrder upOrder = upOrderService.findByShopId(jsonObject.getString("orderNum"));
            jsonObject = new JSONObject();
            jsonObject.put("orderNum", upOrder.getUporderuuid());
            jsonObject.put("phonenum", upOrder.getUpphonenum());
            jsonObject.put("createtime", DateUtils.toLongDate(upOrder.getCreatetime()));
            jsonObject.put("status", upOrder.getStatus());
            logger.info("queryOrderDetail:"+jsonObject.toString());
            return ResultMessage.getSucceed(jsonObject.toString());
        }
        return "ok";
    }
}
